﻿using System;
using Orchard.ContentManagement;
using Orchard.Core.Routable.Models;
using Orchard.ContentManagement.Aspects;

namespace Contrib.Chapters.Models {
    public class ChapterPart : ContentPart<ChapterPartRecord>, IComparable<ChapterPart> {
        
        public string Title {
            get { return this.As<RoutePart>().Title; }
            set { this.As<RoutePart>().Title = value; }
        }

        public string Slug {
            get { return this.As<RoutePart>().Slug; }
            set { this.As<RoutePart>().Slug = value; }
        }

        public string Path {
            get { return this.As<RoutePart>().Path; }
            set { this.As<RoutePart>().Path = value; }
        }

        public IContent Container {
            get { return this.As<ICommonPart>().Container; }
            set {
                this.As<ICommonPart>().Container = value;
                _levels = -1;
            }
        }

        public int Position {
            get { return Record.Position; }
            set { Record.Position = value; }
        }

        private int _levels = -1;

        public int Level { 
            get { 
                if(_levels == -1) {
                    if (Container == null) {
                        throw new NotSupportedException();
                    }
                    
                    if(Container.Has<BookPart>()) {
                        return 0;
                    }

                    _levels = Container.As<ChapterPart>().Level + 1;
                }

                return _levels;
            }
        }

        #region IComparable<ChapterPart> Members

        public int CompareTo(ChapterPart other) {
            return other.Container.As<IRoutableAspect>().Path == this.Container.As<IRoutableAspect>().Path
                       ? Position.CompareTo(other.Position)
                       : Path.CompareTo(other.Path);
        }

        #endregion
    }
}